/*
 *  Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "modules/audio_processing/agc2/noise_level_estimator.h"

#include <array>
#include <functional>
#include <limits>

#include "modules/audio_processing/agc2/agc2_testing_common.h"
#include "modules/audio_processing/agc2/vector_float_frame.h"
#include "modules/audio_processing/logging/apm_data_dumper.h"
#include "rtc_base/gunit.h"
#include "rtc_base/random.h"

namespace webrtc {
namespace {
Random rand_gen(42);
ApmDataDumper data_dumper(0);
constexpr int kNumIterations = 200;
constexpr int kFramesPerSecond = 100;

// Runs the noise estimator on audio generated by 'sample_generator'
// for kNumIterations. Returns the last noise level estimate.
float RunEstimator(std::function<float()> sample_generator, int rate) {
  NoiseLevelEstimator estimator(&data_dumper);
  const size_t samples_per_channel =
      rtc::CheckedDivExact(rate, kFramesPerSecond);
  VectorFloatFrame signal(1, static_cast<int>(samples_per_channel), 0.f);

  for (int i = 0; i < kNumIterations; ++i) {
    AudioFrameView<float> frame_view = signal.float_frame_view();
    for (size_t j = 0; j < samples_per_channel; ++j) {
      frame_view.channel(0)[j] = sample_generator();
    }
    estimator.Analyze(frame_view);
  }
  return estimator.Analyze(signal.float_frame_view());
}

float WhiteNoiseGenerator() {
  return static_cast<float>(rand_gen.Rand(std::numeric_limits<int16_t>::min(),
                                          std::numeric_limits<int16_t>::max()));
}
}  // namespace

// White random noise is stationary, but does not trigger the detector
// every frame due to the randomness.
TEST(AutomaticGainController2NoiseEstimator, RandomNoise) {
  for (const auto rate : {8000, 16000, 32000, 48000}) {
    const float noise_level = RunEstimator(WhiteNoiseGenerator, rate);
    EXPECT_NEAR(noise_level, -5.f, 1.f);
  }
}

// Sine curves are (very) stationary. They trigger the detector all
// the time. Except for a few initial frames.
TEST(AutomaticGainController2NoiseEstimator, SineTone) {
  for (const auto rate : {8000, 16000, 32000, 48000}) {
    test::SineGenerator gen(600.f, rate);
    const float noise_level = RunEstimator(gen, rate);
    EXPECT_NEAR(noise_level, -33.f, 1.f);
  }
}

// Pulses are transient if they are far enough apart. They shouldn't
// trigger the noise detector.
TEST(AutomaticGainController2NoiseEstimator, PulseTone) {
  for (const auto rate : {8000, 16000, 32000, 48000}) {
    test::PulseGenerator gen(20.f, rate);
    const int noise_level = RunEstimator(gen, rate);
    EXPECT_NEAR(noise_level, -79.f, 1.f);
  }
}

}  // namespace webrtc
